package speedchina.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import speedchina.constant.UserConstants;
import speedchina.dao.user.RoleDeptMapper;
import speedchina.dao.user.RoleMapper;
import speedchina.dao.user.RoleResourceMapper;
import speedchina.entity.user.*;
import speedchina.enums.ResultEnum;
import speedchina.exception.BaseException;
import speedchina.service.user.RoleDeptService;
import speedchina.service.user.RoleResourceService;
import speedchina.service.user.RoleService;
import speedchina.service.user.UserRoleService;
import speedchina.util.Convert;
import speedchina.util.security.ShiroUtils;

import java.util.*;


/**
 * @author earthchen
 * @date 2018/9/27
 **/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService
{
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private RoleDeptMapper roleDeptMapper;

    @Autowired
    private RoleDeptService roleDeptService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Override
    public List<Role> selectRoleAll()
    {
        return list(new QueryWrapper<>());
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int insertRole(Role role)
    {
        role.setCreateBy(ShiroUtils.getLoginName());
        role.setUpdateBy(ShiroUtils.getLoginName());
        role.setDataScope("1");
        role.setDelFlag("0");
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        // 新增角色信息
        save(role);
        ShiroUtils.clearCachedAuthorizationInfo();
        return insertRoleResource(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleResource(Role role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<RoleResource> list = new ArrayList<RoleResource>();
        for (Long resourceId : role.getResourceIds())
        {
            RoleResource rm = new RoleResource();
            rm.setRoleId(role.getId());
            rm.setResourceId(resourceId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            roleResourceService.saveBatch(list);
        }
        return list.size();
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public Role selectRoleById(Long roleId)
    {
        return getById(roleId);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRole(Role role)
    {
        role.setUpdateBy(ShiroUtils.getLoginName());
        role.setUpdateTime(new Date());
        // 修改角色信息
        updateById(role);
        ShiroUtils.clearCachedAuthorizationInfo();
        // 删除角色与菜单关联
        roleResourceService.remove(new QueryWrapper<RoleResource>().eq("role_id", role.getId()));
        return insertRoleResource(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public void updateRule(Role role)
    {
        role.setUpdateBy(ShiroUtils.getLoginName());
        if (role.getId() == null)
        {
            throw new BaseException(ResultEnum.UPDATE_HAVE_TO_ID);
        }
        // 修改角色信息
        updateById(role);
        // 删除角色与部门关联
        roleDeptService.remove(new QueryWrapper<RoleDept>().eq("role_id", role.getId()));
        // 新增角色和部门信息（数据权限）
        insertRoleDept(role);
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public void insertRoleDept(Role role)
    {
        // 新增角色与部门（数据权限）管理
        List<RoleDept> list = new ArrayList<RoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            RoleDept rd = new RoleDept();
            rd.setRoleId(role.getId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            roleDeptService.saveBatch(list);
        }
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public int deleteRoleByIds(String ids)
        throws Exception
    {
        Long[] roleIds = Convert.toLongArray(ids);
        for (Long roleId : roleIds)
        {
            Role role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new Exception(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return roleMapper.deleteRoleByIds(roleIds);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleService.count(new QueryWrapper<UserRole>().eq("role_id", roleId));
    }

    @Override
    public Set<String> selectRoleKeys(Long userId)
    {
        List<Role> perms = roleMapper.selectRolesByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (Role perm : perms)
        {
            permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public List<Role> selectRolesByUserId(Long userId)
    {
        List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
        List<Role> roles = selectRoleAll();
        for (Role role : roles)
        {
            for (Role userRole : userRoles)
            {
                if (role.getId().longValue() == userRole.getId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    @Override
    public boolean deleteRoleById(Long roleId)
    {
        Role role = selectRoleById(roleId);
        if (countUserRoleByRoleId(roleId) > 0)
        {
            throw new BaseException(String.format("%1$s已分配,不能删除", role.getRoleName()));
        }
        return removeById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(Role role)
    {
        Long roleId = role.getId() == null ? -1L : role.getId();
        Role info = getOne(new QueryWrapper<Role>().eq("role_name", role.getRoleName()));
        if (info != null && info.getId().longValue() != roleId.longValue())
        {
            return UserConstants.ROLE_NAME_NOT_UNIQUE;
        }
        return UserConstants.ROLE_NAME_UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(Role role)
    {
        Long roleId = role.getId() == null ? -1L : role.getId();
        Role info = getOne(new QueryWrapper<Role>().eq("role_name", role.getRoleName()));
        if (info != null && info.getId().longValue() != roleId.longValue())
        {
            return UserConstants.ROLE_KEY_NOT_UNIQUE;
        }
        return UserConstants.ROLE_KEY_UNIQUE;
    }
}
